package com.ttxs.uaa.api.common;

import com.ttxs.common.core.vo.R;
import com.ttxs.common.core.utils.AuthUtils;
import com.ttxs.common.core.constant.Api;
import com.ttxs.uaa.entity.SysUser;
import com.ttxs.uaa.service.ISysUserService;
import com.ttxs.uaa.vo.LoginResult;
import com.ttxs.uaa.vo.LoginVO;
import com.ttxs.uaa.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping(Api.Common.Login.PREFIX)
@RequiredArgsConstructor
@Slf4j
public class LoginApi {
    private final ISysUserService sysUserService;

    @PostMapping(Api.Common.Login.LOGIN)
    public R login(@RequestBody LoginVO loginVO) {
        LoginResult loginResult = sysUserService.login(loginVO.getPlatformName(), loginVO.getUsername(), loginVO.getPassword());
        if(loginResult.isSuccess()) {
            if (log.isDebugEnabled()) {
                log.debug("=======================登录成功========================");
                log.debug("userId:{}", loginResult.getUserId());
                log.debug("nickName:{}", loginResult.getNickName());
                log.debug("roleNames:{}", loginResult.getRoleNames());
                log.debug("platformId:{}", loginResult.getPlatformId());
                log.debug("platformName:{}", loginResult.getPlatformName());
                log.debug("tokenCreateTime:{}", DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss:SSS").format(LocalDateTime.ofInstant(Instant.ofEpochMilli(loginResult.getTokenCreateTime()), ZoneId.systemDefault())));
                log.debug("tokenExpireTime:{}", DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss:SSS").format(LocalDateTime.ofInstant(Instant.ofEpochMilli(loginResult.getTokenExpireTime()), ZoneId.systemDefault())));
                log.debug("=======================登录日志结束=======================\n");
            }
            return R.ok(loginResult);
        } else {
            return R.error(loginResult.getMessage());
        }
    }

    @PostMapping(Api.Common.Login.REGISTER)
    public R register(@RequestBody UserVO userVO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userVO, sysUser);
        try {
            return sysUserService.register(sysUser) ?
                    R.ok() : R.error("注册失败");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @GetMapping(Api.Common.Login.LOGOUT)
    public R logout(@RequestHeader String token) {
        AuthUtils.removeToken(token);
        return R.ok();
    }
}
